// pages/index/water/water.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    current:"1",
    money:"10",
    userInfo:{},
    paymentInfo:{}
  },
  /**
   * 生命周期函数--页面显示
   */
  onShow:function(){
    this.getData()
  },
  //选择改变充值金额
  changeMoney(e){
    var current = e.currentTarget.dataset.current;
    var money = e.currentTarget.dataset.money;
    this.setData({
      current,
      money
    })
  },
  //输入自定义金额
  moneyInput(e) {
    let price = e.detail.value;
    price = price.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    price = price.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    price = price.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    price = price.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    // 去除整数前的0和小数点后多余的0，如011.020300 =》 11.0203
    const reg1 = /0*([1-9]\d*|0\.\d+)/;
    const reg2 = /(?:\.0*|(\.\d+?)0+)$/;
    price = price.replace(reg1, '$1').replace(reg2, '$1');
    this.setData({
      money:price
    })
   },
  //网络请求，获取数据
  getData(){
    // 获取用户数据
    app.$http.get('/app/user/'+wx.getStorageSync('userId')).then(res =>{
      // 获取缴费数据
      app.$http.get('/app/payment/select',{address:res.data.address}).then(resp =>{
        this.setData({
          userInfo:res.data,
          paymentInfo:resp.data.records.length==0?{waterFee:0,electricFee:0}:resp.data.records[0]
        })
      }).catch(err => {
        console.log(err)
      })
    }).catch(err => {
      console.log(err)
    })
  },
  //跳转到设置住址页面
  toEditAddress(e){
    var current = e.currentTarget.dataset.current;
    wx.navigateTo({url: '/pages/my/profile/edit/edit?current=' + current})
  },
  //跳转到钱包余额页面
  toWallet(){
    wx.navigateTo({url: '/pages/my/wallet/wallet'})
  },
  //submit 缴电费提交
  submit(){
    let form = {address:this.data.userInfo.address,userId:wx.getStorageSync('userId'),electricFee:this.data.money?this.data.money:0}
    if(form.electricFee>this.data.userInfo.money){
      wx.showToast({
        title: '用户余额不足',
        icon:'error',
        duration:1000
      })
      return 0
    }
    app.$http.post('/app/payment/pay',form).then(res=>{
      setTimeout(function() {
        wx.navigateBack()
      }, 1000);
      wx.showToast({
        title: '缴费成功',
        icon:'success',
        duration:1000
      })
    }).catch(err=>{
      console.log(err)
    })
   }
})